<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
import {
  Drawer,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
} from './drawer'

defineOptions({
  name: 'FmSpringDrawer',
})

const props = withDefaults(
  defineProps<{
    modelValue?: boolean
    title: string
    description?: string
    showConfirmButton?: boolean
    showCancelButton?: boolean
    confirmButtonText?: string
    cancelButtonText?: string
    confirmButtonDisabled?: boolean
    confirmButtonLoading?: boolean
    header?: boolean
    footer?: boolean
    closeOnClickOverlay?: boolean
    closeOnPressEscape?: boolean
    contentClass?: HTMLAttributes['class']
    headerClass?: HTMLAttributes['class']
    footerClass?: HTMLAttributes['class']
  }>(),
  {
    modelValue: false,
    showConfirmButton: true,
    showCancelButton: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    confirmButtonDisabled: false,
    confirmButtonLoading: false,
    header: true,
    footer: true,
    closeOnClickOverlay: true,
    closeOnPressEscape: true,
  },
)

const emits = defineEmits<{
  'update:modelValue': [value: boolean]
  'open': []
  'opened': []
  'close': []
  'closed': []
  'confirm': []
  'cancel': []
}>()

const isOpen = ref(props.modelValue)

watch(() => props.modelValue, (newValue) => {
  isOpen.value = newValue
})

function updateOpen(value: boolean) {
  isOpen.value = value
  emits('update:modelValue', value)
  if (value) {
    emits('open')
  }
  else {
    emits('close')
  }
}

function onConfirm() {
  updateOpen(false)
  emits('confirm')
}

function onCancel() {
  updateOpen(false)
  emits('cancel')
}
</script>

<template>
  <Drawer :open="isOpen" @update:open="updateOpen">
    <DrawerContent>
      <DrawerHeader v-if="header" :class="headerClass">
        <slot name="header">
          <DrawerTitle>{{ title }}</DrawerTitle>
          <DrawerDescription class="empty:hidden">
            {{ description }}
          </DrawerDescription>
        </slot>
      </DrawerHeader>
      <div :class="cn('flex-col-center p-4', contentClass)">
        <slot />
      </div>
      <DrawerFooter v-if="footer" :class="footerClass">
        <slot name="footer">
          <FmButton v-if="showConfirmButton" :disabled="confirmButtonDisabled" :loading="confirmButtonLoading" @click="onConfirm">
            {{ confirmButtonText }}
          </FmButton>
          <FmButton v-if="showCancelButton" variant="outline" @click="onCancel">
            {{ cancelButtonText }}
          </FmButton>
        </slot>
      </DrawerFooter>
    </DrawerContent>
  </Drawer>
</template>
